var Login = function(email, password, options){
	this.email = email;
	this.password = password;
	this.success = options.success;
	this.error = options.error;
	this.login();
};

Login.prototype._error = function(code, message){
	if(typeof this.error == 'function') {
		this.error(code, message);
	}
};

Login.prototype._success = function(data){
	if(typeof this.success == 'function') {
		this.success(data);
	}
};

Login.prototype.login = function(){
	var self = this;
	var email = Mysql.escape(this.email);
	var password = components.string.encryptPassword(this.password);
	Mysql.query("SELECT id,email,name,password,COUNT(*) as c1 FROM Account WHERE email="+email).on('error', function(error){
		console.log('Mysql error: '+error);
		self.error(9999, 'Mysql error');
		return;
	}).on('result', function(result){
		if(result.c1 == 0) {
			self._error(9999, 'Not found account');
			return;
		}
		if(result.password !== password) {
			self._error(9999, 'Password invalid');
			return;
		}
		delete result.password;
		delete result.c1;
		var account = result;
		var tokenService = new (Services('token'))(account.id, {
			success: function(data){
				account.token = data;
				self._success(account);
			},
			error: function(code, message){
				self._error(code, message);
			}
		});
	});
};

module.exports = Login;